package com.estronger.shopmanage.ui.common;

import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.estronger.shopmanage.R;
import com.estronger.shopmanage.base.BaseActivity;
import com.estronger.shopmanage.base.MyApplication;
import com.estronger.shopmanage.bean.B16PlanMeasure;
import com.estronger.shopmanage.bean.B16PlanMeasure.MeasureGoods;
import com.estronger.shopmanage.bean.B34BuildDetailGoods;
import com.estronger.shopmanage.bean.B34BuildDetailGoods.BuildGoodsItem;
import com.estronger.shopmanage.bean.BeanBase;
import com.estronger.shopmanage.manager.NetManager;
import com.estronger.shopmanage.ui.measure.MeasureActivity;
import com.estronger.shopmanage.utils.ConvertUtils;
import com.estronger.shopmanage.utils.TimeUtils;
import com.estronger.shopmanage.utils.Toast;
import com.estronger.shopmanage.view.AppDialog;
import com.lidroid.xutils.http.RequestParams;

import org
		.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class ConfirmActivity extends BaseActivity implements
		OnCheckedChangeListener {

	private TextView tv_client, tv_actual_time, tv_other_time,
			tv_condition_text;
	// 这里的measureid还代表了sendID和buildid
	private String measureid, ctsName, ctsTime;
	private EditText et_confirmdesc;
	private RequestParams params;
	protected boolean canselResult = false;
	private CheckBox cb_actual, cb_other, cb_no_sure;
	// 测量-送货-安装的确认预约都是这个Activity，分别由下面1-2-3表示
	private final int MEASURE = 1, SEND = 2, BUILD = 3;
	private int taskid;

	@Override
	protected void init() {
		taskid = getIntent().getIntExtra("taskid", 2);
		measureid = getIntent().getStringExtra("measureid");
		ctsName = getIntent().getStringExtra("ctsName");
		ctsTime = getIntent().getStringExtra("ctsTime");
	}

	// 初始化各个View
	@Override
	protected void initView() {
		setContentView(R.layout.activity_confirm_time);

		tv_client = (TextView) findViewById(R.id.confirm_name_real);

		tv_actual_time = (TextView) findViewById(R.id.confirm_actual_time);
		tv_other_time = (TextView) findViewById(R.id.confirm_other_time);
		cb_actual = (CheckBox) findViewById(R.id.actual_cb);
		cb_other = (CheckBox) findViewById(R.id.other_time_cb);
		cb_no_sure = (CheckBox) findViewById(R.id.no_sure_cb);

		confirm_group = (LinearLayout) findViewById(R.id.confirm_group);
		et_confirmdesc = (EditText) findViewById(R.id.confirmdesc);
		// 根据测量-送货-安装获取详情，分别由1-2-3表示
		if (taskid == MEASURE) {
			RequestParams params = new RequestParams();
			params.addBodyParameter("sf_action", "getplanmeasure");
			params.addBodyParameter("usercode", MyApplication.getUserCode());
			params.addBodyParameter("measureid", measureid);
			connect(params, NetManager.DETAIL);
		} else if (taskid == SEND) {
			et_confirmdesc.setVisibility(View.GONE);
			tv_client.setText(ctsName);
			tv_actual_time.setText(ctsTime);
		} else if (taskid == BUILD) {
			RequestParams params = new RequestParams();
			params.addBodyParameter("sf_action", "getistinfo");
			params.addBodyParameter("usercode", MyApplication.getUserCode());
			params.addBodyParameter("dlvid", measureid);
			connect(params, NetManager.BUILD_DETAIL);
		}

	}

	// 预约时间是单选
	@Override
	protected void initAction() {
		// actual_time.setText(TimeUtils.formatTime(System.currentTimeMillis(),
		// ""));
		tv_other_time.setText(TimeUtils.formatTime(System.currentTimeMillis(),
				""));
		// finish_date.setText(TimeUtils.formatTime(System.currentTimeMillis(),
		// "yyyy-MM-dd"));
		cb_actual.setOnCheckedChangeListener(this);
		cb_other.setOnCheckedChangeListener(this);
		cb_no_sure.setOnCheckedChangeListener(this);
	}

	// 做单选处理，一种预约时间选中同时取消其他两个
	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		switch (buttonView.getId()) {
		case R.id.actual_cb:
			if (isChecked) {
				cb_no_sure.setChecked(false);
				cb_other.setChecked(false);
			}
			break;
		case R.id.other_time_cb:
			if (isChecked) {
				cb_no_sure.setChecked(false);
				cb_actual.setChecked(false);
			}
			break;
		case R.id.no_sure_cb:
			if (isChecked) {
				cb_actual.setChecked(false);
				cb_other.setChecked(false);
			}
			break;
		}
	}

	private LinearLayout condition_group, confirm_group;
	private String[] pos = { "①", "②", "③", "④", "⑤", "⑥", "⑦", "⑧", "⑨", "⑩" };
	private ImageView goods_img;
	private TextView goods_name, goods_count, goods_property, goods_feature;

	@Override
	protected void onNetSuccess(int code, String result) {
		super.onNetSuccess(code, result);

		if (NetManager.CONFIRM == code) {
			BeanBase bean = gson.fromJson(result, BeanBase.class);
			if (bean.success) {
				Toast.show(this, "提交成功", 2000);
				setResult(MeasureActivity.REFLESH_DATA);
				finish();
			} else {
				Toast.show(this, bean.msg, 2000);
			}
		}
		if (NetManager.DETAIL == code) {
			initMeasureItem(result);
		}
		if (NetManager.BUILD_DETAIL == code) {
			initBuildItem(result);
		}
	}

	/**
	 * 初始化安装确认时的货物
	 * 
	 * @param result
	 *            货物信息
	 */
	public void initBuildItem(String result) {
		B34BuildDetailGoods detail = gson.fromJson(result,
				B34BuildDetailGoods.class);
		tv_client.setText(ConvertUtils.formatNullF(detail.data.buildname) + detail.data.cstname);
		tv_actual_time.setText(detail.data.pidate);
		// 测量货物的详细信息
		for (int i = 0; i < detail.data.istitem.size(); i++) {
			BuildGoodsItem data = detail.data.istitem.get(i);
			View v = View.inflate(this, R.layout.goods_condition, null);
			goods_name = (TextView) v.findViewById(R.id.goods_name);
			goods_count = (TextView) v.findViewById(R.id.goods_count);
			goods_property = (TextView) v.findViewById(R.id.goods_property);
			goods_img = (ImageView) v.findViewById(R.id.goods_item_img);
			goods_feature = (TextView) v.findViewById(R.id.goods_feature);

			v.setTag(data.dlvitemid);

			goods_name.setText(data.goodsname);
			goods_property.setText(data.sizedesc);
			goods_count.setText(data.qty);
			goods_feature.setText(data.unitname);
			MyApplication.imageLoader.displayImage(NetManager.getDownloadURL()
					+ "?filepath=" + data.simplepicfile, goods_img);
			condition_group = (LinearLayout) v
					.findViewById(R.id.item_conditions);
			for (int j = 0; j < data.conditionitem.size(); j++) {
				View item = View.inflate(this, R.layout.condition_item, null);
				// TextView pos_tv = (TextView)
				// item.findViewById(R.id.condition_position);
				TextView content = (TextView) item
						.findViewById(R.id.condition_content);
				CheckBox cb = (CheckBox) item.findViewById(R.id.condition_cb);

				item.setTag(data.conditionitem.get(j).itemid);
				// pos_tv.setText(pos[j]);
				content.setText(data.conditionitem.get(j).content);
				if ("1".equals(data.conditionitem.get(j).ifcheck)) {
					cb.setChecked(true);
				}
				condition_group.addView(item);
			}
			confirm_group.addView(v);
		}
	}

	/**
	 * 初始化测量确认时的货物
	 * 
	 * @param result
	 *            货物信息
	 */
	public void initMeasureItem(String result) {
		B16PlanMeasure detail = gson.fromJson(result, B16PlanMeasure.class);
		tv_client.setText(ConvertUtils.formatNullF(detail.data.buildname) + detail.data.cstname);
		tv_actual_time.setText(detail.data.planmeasuredate);
		// 测量货物的详细信息
		for (int i = 0; i < detail.data.measureitem.size(); i++) {
			MeasureGoods data = detail.data.measureitem.get(i);
			View v = View.inflate(this, R.layout.goods_condition, null);
			goods_name = (TextView) v.findViewById(R.id.goods_name);
			goods_count = (TextView) v.findViewById(R.id.goods_count);
			goods_property = (TextView) v.findViewById(R.id.goods_property);
			goods_img = (ImageView) v.findViewById(R.id.goods_item_img);
			goods_feature = (TextView) v.findViewById(R.id.goods_feature);
			tv_condition_text = (TextView) v.findViewById(R.id.condition_text);
			tv_condition_text.setText("测量条件");

			v.setTag(data.measureitemid);

			goods_name.setText(data.goodsname);
			goods_property.setText(data.sizedesc);
			goods_count.setText(data.qty);
			goods_feature.setText(data.unitname);
			MyApplication.imageLoader.displayImage(NetManager.getDownloadURL()
					+ "?filepath=" + data.simplepicfile, goods_img);
			condition_group = (LinearLayout) v
					.findViewById(R.id.item_conditions);
			for (int j = 0; j < data.conditionitem.size(); j++) {
				View item = View.inflate(this, R.layout.condition_item, null);
				// TextView pos_tv = (TextView)
				// item.findViewById(R.id.condition_position);
				TextView content = (TextView) item
						.findViewById(R.id.condition_content);
				CheckBox cb = (CheckBox) item.findViewById(R.id.condition_cb);

				item.setTag(data.conditionitem.get(j).itemid);
				// pos_tv.setText(pos[j]);
				content.setText(data.conditionitem.get(j).content);
				if ("1".equals(data.conditionitem.get(j).ifcheck)) {
					cb.setChecked(true);
				}
				condition_group.addView(item);
			}
			confirm_group.addView(v);
		}
	}

	/**
	 * 预约确认后向服务器保存信息
	 * 
	 * @param view
	 */
	public void save(View view) {
		String planmeasuredatetype, newplanmeasuredate = null;
		if (cb_actual.isChecked()) {
			planmeasuredatetype = "0";
			// newplanmeasuredate = actual_time.getText().toString();
		} else if (cb_other.isChecked()) {
			planmeasuredatetype = "1";
			newplanmeasuredate = tv_other_time.getText().toString();
		} else {
			planmeasuredatetype = "2";
		}

		String confirm = et_confirmdesc.getText().toString().trim();

		showDialog("数据提交中...", true);
		params = new RequestParams();
		params.addBodyParameter("usercode", MyApplication.getUserCode());
		if (taskid == MEASURE) { // 这里提交测量确认信息
			String measureitem = buildJson("measureitemid");
			params.addBodyParameter("sf_action", "confirmfinish");
			params.addBodyParameter("measureid", measureid);
			params.addBodyParameter("planmeasuredatetype", planmeasuredatetype);
			params.addBodyParameter("newplanmeasuredate", newplanmeasuredate);
			params.addBodyParameter("confirmdesc", confirm);
			params.addBodyParameter("measureitem", measureitem);
		} else if (taskid == SEND) { // 这里提交送货确认信息
			params.addBodyParameter("sf_action", "dlvconfirmfinish");
			params.addBodyParameter("dlvid", measureid);
			params.addBodyParameter("pddatetype", planmeasuredatetype);
			params.addBodyParameter("newpddate", newplanmeasuredate);
		} else if (taskid == BUILD) { // 这里提交安装确认信息
			String measureitem = buildJson("dlvitemid");
			params.addBodyParameter("sf_action", "istconfirmfinish");
			params.addBodyParameter("dlvid", measureid);
			params.addBodyParameter("pidatetype", planmeasuredatetype);
			params.addBodyParameter("newpidate", newplanmeasuredate);
			params.addBodyParameter("istconfirmdesc", confirm);
			params.addBodyParameter("dlvitem", measureitem);
		}

		connect(params, NetManager.CONFIRM);
	}

	// 组成提交到服务器的json
	private String buildJson(String id) {
		try {
			JSONArray goods = new JSONArray();
			for (int i = 0; i < confirm_group.getChildCount(); i++) {
				RelativeLayout item = (RelativeLayout) confirm_group.getChildAt(i);
				JSONObject jsonObj = new JSONObject();
				jsonObj.put(id, item.getTag());

				JSONArray conditionitem = new JSONArray();
				LinearLayout condition_group = (LinearLayout) item
						.findViewById(R.id.item_conditions);
				for (int j = 0; j < condition_group.getChildCount(); j++) {
					RelativeLayout v = (RelativeLayout) condition_group
							.getChildAt(j);
					CheckBox cb = (CheckBox) v.findViewById(R.id.condition_cb);
					String ifcheck;
					if (cb.isChecked()) {
						ifcheck = "1";
					} else {
						ifcheck = "0";
					}
					JSONObject conditionObj = new JSONObject();
					conditionObj.put("itemid", v.getTag());
					conditionObj.put("ifcheck", ifcheck);
					conditionitem.put(conditionObj);
				}
				jsonObj.put("measureitem", conditionitem);
				goods.put(jsonObj);
			}
			// Log.i("GAOUJ", "BUILD JSON = " +goods.toString());
			return goods.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}

	// 弹出时间选择器
	public void showPicker(View view) {
		if (view.getId() == R.id.confirm_picker1) {
			AppDialog.createPicker(this, tv_actual_time).show();
		} else if (view.getId() == R.id.confirm_picker2) {
			AppDialog.createPicker(this, tv_other_time).show();
		}
	}

	// 是否显示货物的条件
	public void showCondition(View view) {
		ImageView rb = (ImageView) view;
		View condition_group = ((View) view.getParent().getParent())
				.findViewById(R.id.item_conditions);
		if (condition_group.getVisibility() == View.VISIBLE) {
			rb.setBackgroundResource(R.drawable.hide_view_down);
			condition_group.setVisibility(View.GONE);
		} else {
			rb.setBackgroundResource(R.drawable.hide_view_up);
			valueAnim(0, condition_group.getMeasuredHeight(), condition_group);
			condition_group.setVisibility(View.VISIBLE);
		}
	}

	public void close(View v) {
		finish();
	}
}
